import { Form, Input, Modal, Select } from 'antd';
import { useEffect, useState } from 'react';

interface IProps {
  roleList: ROLE.RoleType[];
  currentUser: SYSTEMUSER.UserType;
  onSubmit: (value: SYSTEMUSER.EditRoleParams) => void;
}

const EditUserModal: React.FC<IProps> = ({ roleList, currentUser, onSubmit }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [userForm] = Form.useForm();

  const onOk = async () => {
    const fields = await userForm.validateFields();
    onSubmit({ ...fields, id: currentUser.id });
    setIsOpen(false);
  };

  useEffect(() => {
    userForm.setFieldsValue({
      userName: currentUser.userName,
      systemRole: currentUser.systemRole,
    });
  }, []);

  return (
    <>
      <a
        key="user_Edit"
        onClick={() => {
          setIsOpen(true);
        }}
      >
        编辑
      </a>
      <Modal
        title="编辑用户"
        open={isOpen}
        onCancel={() => {
          setIsOpen(false);
        }}
        onOk={onOk}
        destroyOnClose
      >
        <Form form={userForm}>
          <Form.Item
            label="用户名"
            name="userName"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
              {
                pattern: /\w/,
                message: '可输入英文字母，数字，下划线组合的用户名',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="授权角色"
            name="systemRole"
            rules={[
              {
                required: true,
                message: '请选择授权角色',
              },
            ]}
          >
            <Select options={roleList.map((item) => ({ label: item.name, value: item.id }))} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default EditUserModal;
